package com.cocolove2.library_cocodialog.dialogs.base;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.method.ScrollingMovementMethod;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cocolove2.library_cocodialog.listener.AnimListenerAdapter;

import java.lang.ref.WeakReference;

@SuppressWarnings({"unchecked", "unused"})
public abstract class CocoAlertDialogBase<T extends CocoDialogBase> extends CocoDialogBase<T> {
    //title的最小高度48dp
    public final static int DEFAULT_TITLE_MIN_HEIGHT = 48;
    //内容的内间距16dp
    public final static int DEFAULT_CONTENT_PADDING = 16;
    //内容的最小高度为64dp
    public final static int DEFAULT_CONTENT_MIN_HEIGHT = 64;

    /* container*/
    protected LinearLayout mLlContainer;
    /*title*/
    protected TextView mTvTitle;
    /*title content(标题)*/
    protected CharSequence mTitle;
    /* title textcolor(标题颜色)*/
    protected int mTitleTextColor;
    /* title textsize(标题字体大小,单位sp)*/
    protected float mTitleTextSize;
    /*show gravity of title(正文内容显示位置)*/
    protected int mTitleGravity = Gravity.CENTER_VERTICAL;

    /*content*/
    protected TextView mTvMessage;
    /*content text*/
    protected CharSequence mMessage;
    /*show gravity of content(正文内容显示位置)*/
    protected int mMessageGravity = Gravity.CENTER_VERTICAL;
    /* content textcolor(正文字体颜色)*/
    protected int mMessageTextColor;
    /* content textsize(正文字体大小)*/
    protected float mMessageTextSize;
    protected int[] mMessagePadding = {-1, -1, -1, -1};

    /*btn container*/
    protected LinearLayout mLlBtns;
    /* btns*/
    protected TextView mTvBtnNegative;
    protected TextView mTvBtnPositive;
    protected TextView mTvBtnNeutral;
    /* btn text(按钮内容)*/
    protected CharSequence mBtnNegativeText;
    protected CharSequence mBtnPositiveText;
    protected CharSequence mBtnNeutralText;
    /*btn textcolor(按钮字体颜色)*/
    protected int mBtnNegativeTextColor;
    protected int mBtnPositiveTextColor;
    protected int mBtnNeutralTextColor;

    private Message mButtonPositiveMessage;
    private Message mButtonNegativeMessage;
    private Message mButtonNeutralMessage;
    /*按钮字体大小单位(sp)*/
    protected float mBtnTextSize = 14f;
    /*btn press color(按钮点击颜色)*/
    protected int mBtnPressColor = Color.parseColor("#E3E3E3");// #85D3EF,#ffcccccc,#E3E3E3
    /*处理点击效果的handler*/
    private Handler mHandler;
    /* 被点击的按钮*/
    private View mClickBtn;

    private final View.OnClickListener mButtonHandler = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mClickBtn = v;
            if (isHasExitAnim()) {
                dismiss();
            } else {
                doHandelButtonMessage(v);
                // Post a message so we dismiss after the above handlers are executed
                mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, CocoAlertDialogBase.this)
                        .sendToTarget();
            }
        }
    };

    private void doHandelButtonMessage(View v) {
        final Message m;
        if (v == mTvBtnPositive && mButtonPositiveMessage != null) {
            m = Message.obtain(mButtonPositiveMessage);
        } else if (v == mTvBtnNegative && mButtonNegativeMessage != null) {
            m = Message.obtain(mButtonNegativeMessage);
        } else if (v == mTvBtnNeutral && mButtonNeutralMessage != null) {
            m = Message.obtain(mButtonNeutralMessage);
        } else {
            m = null;
        }

        if (m != null) {
            m.sendToTarget();
        }
    }

    public CocoAlertDialogBase(Context context) {
        super(context);
        initView(context);
    }

    public CocoAlertDialogBase(Context context, int style) {
        super(context, style);
        initView(context);
    }

    private void initView(Context context) {
        mHandler = new ButtonHandler(this);

        mLlContainer = new LinearLayout(context);
        mLlContainer.setOrientation(LinearLayout.VERTICAL);
        mLlContainer.setLayoutParams(getDefaultparams());
        mLlContainer.setClickable(true);

        /** title */
        mTvTitle = new TextView(context);
        mTvTitle.setMaxLines(2);
        /** content */
        mTvMessage = new TextView(context);
        mTvMessage.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1));
        /**btns*/
        mLlBtns = new LinearLayout(context);
        mLlBtns.setOrientation(LinearLayout.HORIZONTAL);

        mTvBtnNegative = new TextView(context);
        mTvBtnNegative.setClickable(true);
        mTvBtnNegative.setGravity(Gravity.CENTER);

        mTvBtnNeutral = new TextView(context);
        mTvBtnNeutral.setClickable(true);
        mTvBtnNeutral.setGravity(Gravity.CENTER);

        mTvBtnPositive = new TextView(context);
        mTvBtnPositive.setClickable(true);
        mTvBtnPositive.setGravity(Gravity.CENTER);

        setMessagePadding(-1, -1, -1, -1);
        setOutAnimListener(new AnimListenerAdapter() {
            @Override
            public void onAnimEnd() {
                doHandelButtonMessage(mClickBtn);
            }
        });
    }

    @Override
    protected void setupUiView() {
        /** title */
        if (mTitle != null) {
            mTvTitle.setMinHeight(dp2px(DEFAULT_TITLE_MIN_HEIGHT));
            mTvTitle.setGravity(mTitleGravity);
            mTvTitle.setText(mTitle);
            mTvTitle.setPadding(dp2px(DEFAULT_CONTENT_PADDING), dp2px(DEFAULT_CONTENT_PADDING / 2), dp2px(DEFAULT_CONTENT_PADDING), dp2px(DEFAULT_CONTENT_PADDING / 2));
            mTvTitle.setTextColor(mTitleTextColor);
            mTvTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTitleTextSize);
            mTvTitle.setVisibility(View.VISIBLE);
        } else {
            mTvTitle.setVisibility(View.GONE);
        }

        /** content */
        mTvMessage.setText(mMessage);
        mTvMessage.setPadding(dp2px(mMessagePadding[0]), dp2px(mMessagePadding[1]), dp2px(mMessagePadding[2]), dp2px(mMessagePadding[3]));
        mTvMessage.setMinHeight(dp2px(DEFAULT_CONTENT_MIN_HEIGHT));
        mTvMessage.setGravity(mMessageGravity);
        mTvMessage.setTextColor(mMessageTextColor);
        mTvMessage.setMovementMethod(ScrollingMovementMethod.getInstance());
        mTvMessage.setTextSize(TypedValue.COMPLEX_UNIT_SP, mMessageTextSize);
        mTvMessage.setLineSpacing(0, 1.3f);
        /**btns*/

        mTvBtnNegative.setText(mBtnNegativeText);
        mTvBtnPositive.setText(mBtnPositiveText);
        mTvBtnNeutral.setText(mBtnNeutralText);

        mTvBtnNegative.setTextColor(mBtnNegativeTextColor);
        mTvBtnPositive.setTextColor(mBtnPositiveTextColor);
        mTvBtnNeutral.setTextColor(mBtnNeutralTextColor);

        mTvBtnNegative.setTextSize(TypedValue.COMPLEX_UNIT_SP, mBtnTextSize);
        mTvBtnPositive.setTextSize(TypedValue.COMPLEX_UNIT_SP, mBtnTextSize);
        mTvBtnNeutral.setTextSize(TypedValue.COMPLEX_UNIT_SP, mBtnTextSize);

        mTvBtnNegative.setOnClickListener(mButtonHandler);
        mTvBtnPositive.setOnClickListener(mButtonHandler);
        mTvBtnNeutral.setOnClickListener(mButtonHandler);
    }

    private static final class ButtonHandler extends Handler {
        // Button clicks have Message.what as the BUTTON{1,2,3} constant
        private static final int MSG_DISMISS_DIALOG = 1;

        private WeakReference<DialogInterface> mDialog;

        public ButtonHandler(DialogInterface dialog) {
            mDialog = new WeakReference<>(dialog);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DialogInterface.BUTTON_POSITIVE:
                case DialogInterface.BUTTON_NEGATIVE:
                case DialogInterface.BUTTON_NEUTRAL:
                    ((DialogInterface.OnClickListener) msg.obj).onClick(mDialog.get(), msg.what);
                    break;
                case MSG_DISMISS_DIALOG:
                    ((DialogInterface) msg.obj).dismiss();
            }
        }
    }

    /**
     * 设置title
     */
    public T setTitleStr(CharSequence title) {
        mTitle = title;
        return (T) this;
    }

    /**
     * 设置title的显示位置
     */
    public T setTitleGravity(int titleGravity) {
        mTitleGravity = titleGravity;
        return (T) this;
    }

    /**
     * 设置title的颜色
     */
    public T setTitleTextColor(int titleTextColor) {
        mTitleTextColor = titleTextColor;
        return (T) this;
    }

    /**
     * 设置title的字体的大小
     */
    public T setTitleTextSize(float titleTextSize) {
        mTitleTextSize = titleTextSize;
        return (T) this;
    }

    /**
     * 设置内容
     *
     * @param message 内容不能为空
     */
    public T setMessage(@NonNull CharSequence message) {
        mMessage = message;
        return (T) this;
    }

    /**
     * 设置内容的位置
     */
    public T setMessageGravity(int messageGravity) {
        mMessageGravity = messageGravity;
        return (T) this;
    }


    /**
     * 设置内容的文本颜色
     */
    public T setMessageTextColor(int messageTextColor) {
        mMessageTextColor = messageTextColor;
        return (T) this;
    }

    /**
     * 设置内容的文本的字体大小
     */
    public T setMessageTextSize(float messageTextSize) {
        mMessageTextSize = messageTextSize;
        return (T) this;
    }

    /**
     * 设置message内边距(单位:dp)
     */
    public T setMessagePadding(int left, int top, int right, int bottom) {
        mMessagePadding[0] = left == -1 ? DEFAULT_CONTENT_PADDING : left;
        mMessagePadding[1] = top == -1 ? DEFAULT_CONTENT_PADDING : top;
        mMessagePadding[2] = right == -1 ? DEFAULT_CONTENT_PADDING : right;
        mMessagePadding[3] = bottom == -1 ? DEFAULT_CONTENT_PADDING : bottom;
        return (T) this;
    }

    /**
     * 设置对话框的按钮
     *
     * @param text      文本
     * @param textColor 字体颜色,textColor=0 时则使用默认值
     * @param listener  点击事件
     */
    public T setNegativeButton(CharSequence text, int textColor,
                               DialogInterface.OnClickListener listener) {
        setButton(DialogInterface.BUTTON_NEGATIVE, text, listener, textColor);
        return (T) this;
    }

    /**
     * 设置对话框的按钮
     *
     * @param text      文本
     * @param textColor 字体颜色,textColor=0 时则使用默认值
     * @param listener  点击事件
     */
    public T setNeturalButton(CharSequence text, int textColor,
                              DialogInterface.OnClickListener listener) {
        setButton(DialogInterface.BUTTON_NEUTRAL, text, listener, textColor);
        return (T) this;
    }

    /**
     * 设置对话框的按钮
     *
     * @param text      文本
     * @param textColor 字体颜色,textColor=0 时则使用默认值
     * @param listener  点击事件
     */
    public T setPositiveButton(CharSequence text, int textColor,
                               DialogInterface.OnClickListener listener) {
        setButton(DialogInterface.BUTTON_POSITIVE, text, listener, textColor);
        return (T) this;
    }

    /**
     * 设置按钮的字体大小
     */
    public T setBtnTextSize(float btnTextSize) {
        mBtnTextSize = btnTextSize;
        return (T) this;
    }

    /**
     * 设置按钮按下的颜色
     */
    public T setBtnPressColor(int color) {
        mBtnPressColor = color;
        return (T) this;
    }


    /**
     * Sets a click listener or a message to be sent when the button is clicked.
     * You only need to pass one of {@code listener} or {@code msg}.
     *
     * @param whichButton Which button, can be one of
     *                    {@link DialogInterface#BUTTON_POSITIVE},
     *                    {@link DialogInterface#BUTTON_NEGATIVE}, or
     *                    {@link DialogInterface#BUTTON_NEUTRAL}
     * @param text        The text to display in positive button.
     * @param listener    The {@link DialogInterface.OnClickListener} to use.
     */
    private void setButton(int whichButton, CharSequence text,
                           DialogInterface.OnClickListener listener, int textColor) {
        Message msg = null;
        if (listener != null) {
            msg = mHandler.obtainMessage(whichButton, listener);
        }

        switch (whichButton) {

            case DialogInterface.BUTTON_POSITIVE:
                mBtnPositiveText = text;
                mButtonPositiveMessage = msg;
                if (textColor < 0)
                    mBtnPositiveTextColor = textColor;
                break;

            case DialogInterface.BUTTON_NEGATIVE:
                mBtnNegativeText = text;
                mButtonNegativeMessage = msg;
                if (textColor < 0)
                    mBtnNegativeTextColor = textColor;
                break;

            case DialogInterface.BUTTON_NEUTRAL:
                mBtnNeutralText = text;
                mButtonNeutralMessage = msg;
                if (textColor < 0)
                    mBtnNeutralTextColor = textColor;
                break;

            default:
                throw new IllegalArgumentException("Button does not exist");
        }
    }

}
